# 实时音频 分析
import pyaudio
import numpy as np
import time
from datetime import datetime
import wave
from config import *


def calculate_decibel(data):
    # 将音频数据转换成numpy数组
    samples = np.frombuffer(data, dtype=np.int16)
    # 计算振幅
    peak_amplitude = np.abs(samples).max()
    # 计算分贝
    if peak_amplitude == 0:
        return -np.inf  # 分贝值为负无穷
    else:
        return 20 * np.log10(peak_amplitude / 32768.0)

def audio_decibels(message):
    try:
        p = pyaudio.PyAudio()
        stream = p.open(format=FORMAT,
                        channels=CHANNELS,
                        rate=RATE,
                        input=True,
                        frames_per_buffer=CHUNK,
                        input_device_index=device_id,  # 指定设备的index值
                        )

        while True:
            # 读取音频数据
            data = stream.read(CHUNK)
            # 计算分贝
            db_value = calculate_decibel(data)
            value = [str(datetime.now()), f"{(db_value+dbadd):.0f}"]
            print(value)
            message.put(value,timeout=3)
            time.sleep(0.3)
    except KeyboardInterrupt:
        # 当按下Ctrl+C时退出
        print("停止录音")
    finally:
        # 关闭流和PyAudio对象
        stream.stop_stream()
        stream.close()
        p.terminate()




if __name__ == '__main__':
    pass